////////////////////////////////////////////////////////////////////////////////
///		Labeling challengers that have been in power in the past
////////////////////////////////////////////////////////////////////////////////

*** Finding the list of parties that have been in power in the past 10 years

// Presidential elections
use "$project_path/data/3_cleaned/presidential_elections", clear
drop if flag_inconsequential==1 | flag_coup==1 | flag_not_last==1
keep Country Year Month Type_Election Candidate_1
ren Candidate_1 winner
tempfile pres_winners
save `pres_winners'
use "$project_path/data/1_input/elections/Wikipedia_links/links_pres", clear
ren Candidate winner
drop if winner==""
keep Country Year Month Type_Election winner vdem_party_id
merge 1:1 Country Year Month Type_Election winner using `pres_winners', keep(match) nogen
drop if vdem_party_id==.
drop winner 
tostring vdem_party_id, replace
gen in_power_past_10yrs = ""
sort Type_Election Country Year Month 
forvalues k = 1/10 {
	replace in_power_past_10yrs = in_power_past_10yrs + "," + vdem_party_id[_n-`k'] if Country==Country[_n-`k'] & Year-Year[_n-`k']<=10
}
replace in_power_past_10yrs = substr(in_power_past_10yrs, 2, .)
split in_power_past_10yrs, parse(",")
drop vdem_party_id in_power_past_10yrs
destring in_power_past_10yrs*, replace
tempfile past_power_pres
save `past_power_pres'

// Parliamentary elections
use "$project_path/data/3_cleaned/parliamentary_elections", clear
drop if flag_inconsequential==1 | flag_coup==1 | flag_not_last==1
keep Country Year Month Type_Election Party_1
ren Party_1 winner
tempfile parl_winners
save `parl_winners'
use "$project_path/data/1_input/elections/Wikipedia_links/links_parl", clear
ren Party winner
drop if winner==""
keep Country Year Month Type_Election winner vdem_party_id
merge 1:1 Country Year Month Type_Election winner using `parl_winners', keep(match) nogen
drop if vdem_party_id==.
drop winner 
tostring vdem_party_id, replace
gen in_power_past_10yrs = ""
sort Type_Election Country Year Month 
forvalues k = 1/10 {
	replace in_power_past_10yrs = in_power_past_10yrs + "," + vdem_party_id[_n-`k'] if Country==Country[_n-`k'] & Year-Year[_n-`k']<=10
}
replace in_power_past_10yrs = substr(in_power_past_10yrs, 2, .)
split in_power_past_10yrs, parse(",")
drop vdem_party_id in_power_past_10yrs
destring in_power_past_10yrs*, replace
tempfile past_power_parl
save `past_power_parl'

*** Labeling elections in which the challenger has been in power in the past 10 years

// Presidential elections
use "$project_path/data/3_cleaned/turnovers_presidential", clear
keep Country Year Month Type_Election candidate_opposition
ren candidate_opposition Candidate
merge 1:1 Country Year Month Type_Election Candidate using "$project_path/data/1_input/elections/Wikipedia_links/links_pres", keepusing(vdem_party_id) keep(match) nogen
ren vdem_party_id opp_vdem_id
drop Candidate 
merge 1:1 Country Year Month Type_Election using `past_power_pres', keep(match) nogen
gen opp_in_power_past = .
forvalues k = 1/4 {
	replace opp_in_power_past = 1 if opp_vdem_id==in_power_past_10yrs`k' & opp_vdem_id!=.
}
keep if opp_in_power_past==1
keep Country Year Month Type_Election opp_in_power_past
tempfile opp_in_power_past_pres
save `opp_in_power_past_pres'

// Parliamentary elections
use "$project_path/data/3_cleaned/turnovers_parliamentary_electoral", clear
keep Country Year Month Type_Election party_opposition
ren party_opposition Party
merge 1:1 Country Year Month Type_Election Party using "$project_path/data/1_input/elections/Wikipedia_links/links_parl", keepusing(vdem_party_id) keep(match) nogen
ren vdem_party_id opp_vdem_id
drop Party 
merge 1:1 Country Year Month Type_Election using `past_power_parl', keep(match) nogen
gen opp_in_power_past = .
forvalues k = 1/5 {
	replace opp_in_power_past = 1 if opp_vdem_id==in_power_past_10yrs`k' & opp_vdem_id!=.
}
keep if opp_in_power_past==1
keep Country Year Month Type_Election opp_in_power_past

append using `opp_in_power_past_pres'

tempfile opp_in_power_past
save `opp_in_power_past'

////////////////////////////////////////////////////////////////////////////////
///		Regressions
////////////////////////////////////////////////////////////////////////////////

use "$project_path/data/4_regdata/regdata", clear
merge 1:1 Country Year Month Type_Election using `opp_in_power_past', assert(master match) nogen

log using "$project_path/output/appendix_tables/Appendix_Table_E9.smcl", replace

** Column 1: Baseline
rdrobust diff_m1_chix_econ runvar
rdrobust std_diff_m1_hdi runvar
rdrobust std_diff_m1_democracy_index runvar
rdrobust diff_m1_general_chix runvar

** Column 2: Challengers that have not been previously in power
rdrobust diff_m1_chix_econ runvar if opp_in_power_past!=1
rdrobust std_diff_m1_hdi runvar if opp_in_power_past!=1
rdrobust std_diff_m1_democracy_index runvar if opp_in_power_past!=1
rdrobust diff_m1_general_chix runvar if opp_in_power_past!=1

** Column 3: Challengers that have been previously in power
rdrobust diff_m1_chix_econ runvar if opp_in_power_past==1
rdrobust std_diff_m1_hdi runvar if opp_in_power_past==1
rdrobust std_diff_m1_democracy_index runvar if opp_in_power_past==1
rdrobust diff_m1_general_chix runvar if opp_in_power_past==1

log close


*** Building .tex table
// Regressions 
#delimit ;
local outcomes  
		diff_m1_chix_econ
		std_diff_m1_hdi
		std_diff_m1_democracy_index
		diff_m1_general_chix
;
#delimit cr		

local subsample_count 3

// Initialize matrix of results and define value labels
local ncols = `subsample_count'*2
local nrows = 8
// Prepare matrix of coefficients and other statistics
mat Coefs = J(`nrows', `ncols', .)
mat list Coefs

// Inizialize indices
local row = 1
local next_row = `row' + 1

foreach v in `outcomes'{
	rdrobust `v' runvar, all
	
	//Store estimates and stats
	local b_1: di %5.3f e(tau_cl)
	local se_1: di %5.3f e(se_tau_rb)
	local p_1: di %5.3f e(pv_rb)
	
	rdrobust `v' runvar if opp_in_power_past != 1
	
	//Store estimates and stats
	local b_2: di %5.3f e(tau_cl)
	local se_2: di %5.3f e(se_tau_rb)
	local p_2: di %5.3f e(pv_rb)
	
	rdrobust `v' runvar if opp_in_power_past == 1
	//Store estimates and stats
	local b_3: di %5.3f e(tau_cl)
	local se_3: di %5.3f e(se_tau_rb)
	local p_3: di %5.3f e(pv_rb)
	
	
	forvalues i=1/3{
		mat Coefs[`row',`i'] = `b_`i''
		mat Coefs[`next_row',`i'] = `se_`i''
		mat Coefs[`row',`subsample_count' + `i'] = `p_`i''	
	}
	
	/*
	foreach opp_in_power in "no yes" {
		local ++col     
		local ++pval_col

		if "`opp_in_power'" == "no" {
			rdrobust `v' runvar if opp_in_power_past != 1
		} 
		else if "`opp_in_power'" == "yes" {
			rdrobust `v' runvar if opp_in_power_past == 1
		}

		//Store estimates and stats
		local b_`col': di %5.3f e(tau_cl)
		local se_`col': di %5.3f e(se_tau_rb)
		local p_`col': di %5.3f e(pv_rb)

		mat Coefs[`row',`col'] = `b_`col''
		mat Coefs[`next_row',`col'] = `se_`col''
		mat Coefs[`row',`pval_col'] = `p_`col''
	}*/
	
	local row = `row' + 2
	local next_row = `row' + 1
}
mat list Coefs

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
	// Clear the dataset, and use the matrix as dataset			

	clear
	svmat Coefs

	//	input variable names
	gen varname = ""
	gen temp = _n
	replace varname = "\textbf{Economic performance}" if temp == 1
	replace varname = "SE_1" if temp == 2
	replace varname = "\textbf{HDI}" if temp == 3
	replace varname = "SE_2" if temp == 4
	replace varname = "\textbf{Democracy}" if temp == 5
	replace varname = "SE_3" if temp == 6
	replace varname = "\textbf{General index}" if temp == 7
	replace varname = "SE_4" if temp == 8
	
	order varname, first
	drop temp
	  
	//Adjust the table before exporting
	replace varname = "" if strpos(varname, "SE_")>0
	order varname
	
	// Rename cols and labels
	forvalues n = 1/`subsample_count'{
		rename Coefs`n' Model`n'
	}
	//Cols where we store pvalues
	local n_min = `subsample_count' + 1
	local n_max = `subsample_count'*2
	local i = 1
	forvalues n = `n_min'/`n_max'{
		rename Coefs`n' P_Model`i'
		local ++i
	}
	
	label var varname ""
	label var Model1 "Baseline"
	label var Model2 "Not been prev. in power"
	label var Model3 "Been prev. in power"
	
		
	// Convert to string and add options
	forvalues i = 1/`subsample_count'{
		tostring Model`i', replace force format(%04.3f)
		replace Model`i'= "" if Model`i'=="."
		//Add parenthesis to SE and P-val
		replace Model`i' = "(" + Model`i' + ")" if missing(varname) & Model`i' !=""	

	}
	
	// Add stars
	local 3_star 0.01
	local 2_star 0.05
	local 1_star 0.10
	
	forvalues i = 1/`subsample_count'{
		
		replace Model`i' = Model`i' + "***" if P_Model`i' < `3_star'
		replace Model`i' = Model`i' + "**" if P_Model`i' < `2_star' & P_Model`i' > `3_star'
		replace Model`i' = Model`i' + "*" if P_Model`i' < `1_star' & P_Model`i' > `2_star'
		
		drop P_Model`i'
	}
	
	foreach var of varlist _all {
	qui replace `var' = ustrtrim(`var')	
}

local title = "Heterogeneity with respect to government experience of challengers"
local filename = "quality_bounding"
local output "$project_path/output/appendix_tables/Appendix_Table_E9.tex"
local headerlines = " & & \multicolumn{2}{c}{\textbf{Keeping challengers that have}}"
local footnote = "\caption*{\footnotesize \emph{Notes}: This table presents the results of an exercise in which we restrict the sample to elections in which the challenger has not (resp., has) won elections in the past decade and was plausibly of lower (resp., higher) quality (in column 2, resp. 3). $^{*} p<0.10,^{**} p<0.05,^{***} p<0.01$.}"


	texsave using "`output'", replace title("`title'") varlabels noendash ///
							  footnote("`footnote'") ///
							  headerlines("`headerlines'" "& (1) & (2) & (3) " ) ///
							  frag nofix marker("tab:`filename'") location(H)

